package com.sky.controller.admin;

import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    private final AliOssProperties aliOssProperties;
    private final AliOssUtil aliOssUtil;

    public CommonController(AliOssProperties aliOssProperties, AliOssUtil aliOssUtil) {
        this.aliOssProperties = aliOssProperties;
        this.aliOssUtil = aliOssUtil;
    }

    @RequestMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file)  {

        log.info("文件上传：{}",file);
        try {
            //获取原始文件的名字
            String originalFilename = file.getOriginalFilename();
            //获取后缀
            //String string = originalFilename.split(".")[1];
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            String filepath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filepath);
        } catch (IOException e) {
            log.info("文件上传失败");
            throw new RuntimeException(e);
        }

    }
}
